package com.smartum.mpr.store.local;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import com.smartum.mpr.store.StoreImageProvider;
import com.smartum.mpr.util.BackendConfig;
import com.smartum.mpr.utils.FileUtil;
import com.smartum.mpr.utils.ImageUtil;

public abstract class BaseImageProvider implements StoreImageProvider {

	private String photoFolder;

	public BaseImageProvider(String photoFolder) {
		this.photoFolder = photoFolder;
	}

	@Override
	public String storeImage(MultipartFile file, Long id) throws Exception {
		String appFolder = BackendConfig.getInstance().getAppFolder();

		String relationFilePath = photoFolder + File.separator + String.valueOf(id) + File.separator
		        + System.currentTimeMillis() +"."+ ImageUtil.getImageFormat(file.getOriginalFilename());
		
		String filePath = appFolder + relationFilePath;
		FileUtil.handleUploadedFile(file, filePath);

		return relationFilePath;
	}

	@Override
	public void deleteImage(Long id) throws Exception {
		String appFolder = BackendConfig.getInstance().getAppFolder();
		String filePath = appFolder + photoFolder + File.separator + String.valueOf(id);
		FileUtils.deleteDirectory(new File(filePath));
	}

}
